//场景加载工具类 包含 加载   显示隐藏  飞行  点击事件  字段获取  注册点击事件等功能
export interface HouseholdInfo {
    id: number;
    name?: string;
}

export class LayerManager {
    private viewer: any;
    private sceneUrl: string;
    private layers: Map<string, any> = new Map();

    constructor(viewer: any, sceneUrl: string) {
        this.viewer = viewer;
        this.sceneUrl = sceneUrl;
    }

    /**
     * 加载场景图层
     * 能够直接定位到图层的位置
     */
    async openLayer() {
        const promise = this.viewer.scene.open(this.sceneUrl);
        // const layers = this.viewer.scene.layers.layerQueue;
        await promise;
        promise.then((layerCollection) => {
            layerCollection.forEach((layerCollection) => {
                this.layers.set(layerCollection.name, layerCollection);
                // console.log( `图层 ${layerCollection.name} 加载完成`+  this.layers.get(layerCollection.name));
            });
        });
        console.log(`场景服务加载完成`);
        // layers = this.viewer.scene.layers.find((layer: any) => layer.name.includes('BIM'))
        this.viewer.scene.camera.setView({
            destination: new Cesium.Cartesian3(-2180753.065987198, 4379023.266141494, 4092583.575045952),
            orientation: {
                heading: 4.0392222751147955,
                pitch: 0.010279641987852584,
                roll: 1.240962888005015e-11
            }
        });
    }

    /**
     * 加载场景图层
     * 只是添加图层，不能直接跳转，需要手动跳转
     */
    async loadLayer(layerName: string): Promise<any> {
        const layerUrl = `${this.sceneUrl}/datas/${layerName}`;
        const layer = this.viewer.scene.layers.add(layerUrl);
        layer.setName(layerName);
        this.layers.set(layerName, layer);

        return new Promise((resolve) => {
            layer.readyPromise.then(() => {
                console.log(`图层 ${layerName} 加载完成`);
                resolve(layer);
            });
        });
    }

    /** 设置整个图层显隐 */
    setLayerVisible(layerName: string, visible: boolean): void {
        const layer = this.layers.get(layerName);
        if (layer) {
            // layer.setVisible(visible);
            layer.visible = visible;
            console.log(`图层 ${layerName} 设置为 ${visible ? '可见' : '隐藏'}`);
        } else {
            console.log(`未找到该图层，请检查图层名称是否正确 图层 ${layerName} 不存在`);
        }
    }

    /** 设置某些对象（户型）的显隐 */
    setObjectsVisible(layerName: string, objectIds: number[], visible: boolean): void {
        const layer = this.layers.get(layerName);
        if (layer) {
            layer.setObjsVisibleByIDs(objectIds, visible);
        }
    }

    /** 获取图层所有对象 ID */
    getObjectIds(layerName: string): Promise<number[]> {
        return new Promise((resolve, reject) => {
            const layer = this.layers.get(layerName);
            if (layer) {
                layer.getObjectIds((ids) => resolve(ids));
            } else {
                reject(`图层 ${layerName} 未加载`);
            }
        });
    }

    /** 飞行到指定对象 */
    flyToObject(layerName: string, objectId: number): void {
        const layer = this.layers.get(layerName);
        if (layer) {
            layer.flyToByID(objectId);
        }
    }

    /** 获取对象的字段值 */
    getFieldValue(layerName: string, objectId: number, fieldName: string): Promise<any> {
        return new Promise((resolve, reject) => {
            const layer = this.layers.get(layerName);
            if (layer) {
                layer.getFieldValue(objectId, fieldName, (value) => {
                    resolve(value);
                });
            } else {
                reject(`图层 ${layerName} 未加载`);
            }
        });
    }

    /** 注册点击事件，获取对象ID和属性 */
    registerPickHandler(callback: (info: { layerName: string; objectId: number; properties: Record<string, any> }) => void) {
        this.viewer.scene.eventManager.addEventListener('CLICK', async (event) => {
            const picked = this.viewer.scene.pickObject(event.message.position);
            if (picked && picked.layer) {
                const layerName = picked.layer.name;
                const objectId = picked.ID;

                const props: Record<string, any> = {};
                const fields = ['Name', 'ID', 'Type']; // 可按需修改字段列表
                for (const field of fields) {
                    try {
                        const value = await this.getFieldValue(layerName, objectId, field);
                        props[field] = value;
                    } catch (_) {}
                }

                callback({ layerName, objectId, properties: props });
            }
        });
    }
}
